import model, logging, datetime, os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from sync import SyncManager

def update_testing_ct(test_type):
    if test_type=='compaction':
        tbl = 'compaction_form'
    else:
        tbl = 'asphalt_form'
    sm = SyncManager(tbl)
    data = sm._download()
    results = {}
    for r in data:
        rid = int(r['record']['ID'])
        results.setdefault(rid)
        results[rid] = r['record'][test_type]
    
    
    for r in getattr(model, tbl).all():
        
        setattr(r, test_type, results[r.ID])
        r.put()
        

def summary(tbl):
    m = getattr(model, tbl)
    q = m.all().order('project_key')
    projects = {}
    for r in q:
        projects.setdefault(r.project_key, {})
        if projects[r.project_key]:
            #project already counted
            if projects[r.project_key]['start']>r.form_date:projects[r.project_key]['start'] = r.form_date
            if projects[r.project_key]['end']<r.form_date:projects[r.project_key]['end'] = r.form_date
            projects[r.project_key]['test_count'] += int(getattr(r, tbl.split('_')[0]))
        else:
            #new project
            for k in ['project_number', 'client_name', 'project_name']:
                projects[r.project_key][k] = getattr(r, k)
            projects[r.project_key]['start'] = r.form_date
            projects[r.project_key]['end'] = r.form_date
            projects[r.project_key]['test_count'] = int(getattr(r, tbl.split('_')[0]))
                
    results = []
    
    for k, p in projects.items():
        if p['test_count']>0:
            if p['project_number']:
                pass
            else:
                p['project_number'] = p['project_key']
            for k in [x.lower() for x in 'Complies Accepted Does_not_Comply FM IM ic'.split()]:
                ct = getattr(model, tbl.replace('form', 'test')).all().filter('remarks = ', k).filter('project_number =', p['project_number']).count()
                p[k] = ct
            p['no_remarks'] = getattr(model, tbl.replace('form', 'test')).all().filter('remarks = ', None).filter('project_number =', p['project_number']).count()
            results.append(p)
    nt = getattr(model, tbl.replace('form', 'test')).all().filter('PARENT_RECORD_ID =', 0).count()
    

    
    results.append({'project_number': ' N/A', 'client_name': ' N/A', 'project_name': '', 'start': datetime.datetime(1900,1,1), 'end': datetime.datetime(1900,1,1), 'test_count': nt})
    #query the ones without project number
    return results
            
            
class SummaryHandler(webapp.RequestHandler):
    def get(self):
        action = self.request.get('action')
        if action=='update_compaction_ct':
            update_testing_ct('compaction')
            self.response.out.write('Compaction Count Updated')
            return
        if action=='update_asphalt_ct':
            update_testing_ct('asphalt')
            self.response.out.write('Asphalt Count Updated')
            return
        tbl = self.request.get('tbl')
        path = os.path.join(os.path.dirname(__file__), 'template/summary.html')
        results = summary(tbl)
        header = ['project_number', 'client_name', 'project_name', 'start', 'end', 'test_count', 'accepted', 'complies']
        rows = [header]
        for row in sorted(results, key=lambda x: x['client_name']):
            r = []
            for fld in header:
                if fld in ['start', 'end']:
                    r.append(row.get(fld).strftime('%m/%d/%Y'))
                else:
                    r.append(row.get(fld))
            rows.append(r)
        self.response.out.write(template.render(path, {'rows': rows, 'title': '%s Summary' % tbl}))
            